package com.idanchuang.component.logback.converter;


import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import com.idanchuang.component.core.helper.EnvContext;
import com.idanchuang.component.logback.appender.DcILoggingEvent;
import org.apache.skywalking.apm.toolkit.log.logback.v1.x.LogbackPatternConverter;
import org.apache.skywalking.apm.toolkit.trace.TraceContext;

public class TraceIdPatternConverter extends ClassicConverter {

    @Override
    public String convert(ILoggingEvent iLoggingEvent) {
        if (iLoggingEvent instanceof DcILoggingEvent) {
            return ((DcILoggingEvent) iLoggingEvent).getTraceId();
        }
        return figure(iLoggingEvent);
    }

    /**
     * 整合traceId
     * @return traceId
     */
    public static String figure(ILoggingEvent iLoggingEvent) {
        StringBuilder finalTid = new StringBuilder();
        // 优先选择手动指定的traceId
        String traceId = EnvContext.getDcTraceId();
        if (traceId != null) {
            finalTid.append("dc:").append(traceId).append(";");
        }
        // APM2.0
        String apmTid = org.slf4j.MDC.get("apm-traceid");
        if (apmTid != null) {
            finalTid.append("apm:").append(apmTid).append(";");
        }
        // SkyWalking
        String sky = TraceContext.traceId();
        if (!"TID: N/A".equalsIgnoreCase(sky)) {
            finalTid.append("sky:").append(sky).append(";");
        }
        if (finalTid.length() == 0) {
            finalTid.append("-");
        }
        return finalTid.toString();
    }

}
